2019鐵人賽 Laravel Authentication Hasher因為我本身對 Authentication 已經有初步瞭解,所以我這邊不講使用方法,而是要講一些細節。今天要跟大家聊聊怎麼更改 Laravel 中 Hasher 的加密方式,由於會追點 source code,建議要看這篇的人,可能要有一點點基礎才行。
我們來試看看把 bcrypt 加密模式改為 MD5 加密模式
在開始之前,要先搞懂 Auth::attempt() 是怎麼運作的 參考資料。
我簡單抓個重點,
Auth::attempt() 是在 SessionGuard.php 中時作出來的Auth::attempt() 是在 EloquentUserProvider 中會生成一個 HasherContract $hasher)
$hasher 則用來生成加密的密碼與驗證密碼!HasherContract 則是調用了 use Illuminate\Contracts\Hashing\Hasher as HasherContract;
config\hashing.php 的設定下得知初始設定下的 Hasher 為 BcryptHasher
return [
/*
|--------------------------------------------------------------------------
| Default Hash Driver
|--------------------------------------------------------------------------
|
| This option controls the default hash driver that will be used to hash
| passwords for your application. By default, the bcrypt algorithm is
| used; however, you remain free to modify this option if you wish.
|
| Supported: "bcrypt", "argon", "argon2id"
|
*/
'driver' => 'bcrypt',
];
其實上面的參考資料已經寫得很完整了,只是我用的是 Laravel 5.7,在實作上面出現了點問題,在這裡把解決方法補上
問題如下
會出現這個問題是因為,Hasher 這個 Contracts 一定要要實作以下四種方法 info,make,check,needsRehash
<?php
namespace Illuminate\Contracts\Hashing;
interface Hasher
{
public function info($hashedValue);
public function make($value, array $options = []);
public function check($value, $hashedValue, array $options = []);
public function needsRehash($hashedValue, array $options = []);
}
因此我們只要把 info 的方法補上就可以了(內容是直接複製 BcryptHasher 的做法)
public function info($hashedValue)
{
return $this->driver()->info($hashedValue);
}